package com.intct.hbase.dml;

import com.intct.hbase.util.HBaseConnection;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @author gufg
 * @since 2025-07-11 09:36
 */
public class PutData {
    public static void main(String[] args) throws IOException {
        // put 'ns:t1', '1001', 'f1:name', 'value'
        // 连接HBase
        Connection connection = HBaseConnection.getConnection();

        // 创建TableName实例
        TableName hbaseTableName = TableName.valueOf("intct82", "t001");

        // 创建Admin
        Admin admin = connection.getAdmin();

        // 表存在，则插入数据
        if (admin.tableExists(hbaseTableName)) {

            // 创建Table
            Table table = connection.getTable(hbaseTableName);

            // 插入数据
            Put put = new Put(Bytes.toBytes("1001"));
            put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("name"), Bytes.toBytes("wangwu"));
            put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("age"), Bytes.toBytes("30"));
            put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("sex"), Bytes.toBytes("N"));

            try {
                table.put(put);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (table != null) {
                    table.close();
                }
            }

        } else {
            System.out.println("表不存在，无法插入数据！");
        }

        if (admin != null) {
            admin.close();
        }
    }
}
